# 版本说明:  2024.11.28 新建
# 制作人员:  dzy
# 功能说明： 模拟post请求，替代apifox，方便灵活配置数据
# 备注说明：
# 环境要求： python3/ windows32or64
# 设备要求：


# ---内置库---
import os
import sys
import time
import json

# ---第三方库---
from colorama import init, Fore, Back, Style
import requests
import pyperclip

# ---自研库---
from lib.mytools import getNowTime
from lib.mytools import basicClass
# from mytools import getNowTime
# from mytools import basicClass


class MES_Test_Api_Helper(basicClass):
    def __init__(self):
        super().__init__()
        self.instanceName = 'MP_MES_Test_Api_Helper'
        self.target_server_url = 'http://172.19.64.168:8083'  # 模拟api发送的平台
        self.targetc_uri = '/test/createOrToProcess'
        self.targetc_uri = '/deviceApi/checkProductMoveOut'
        self.set_header()

    def to_dict(self):
        # 电芯进站校验（开始） /deviceApi/checkProductMoveInAndStart
        # 执行完成后 会在对应的工序排队(下一步是进站)
        self.target_input_json = {
            "equipment_id": "SP1RLCS0001",  # 设备*
            "operator_name": "",  # 操作人
            "process_id": "RLCS",  # 工序* XXSS RLCS
            "productBatchNoList": ['0IJ1BDCOL015015USE9C0001']  # 电芯条码列表*
        }

    def set_header(self):
        # 这个是 模拟api平台 http://172.19.64.168:8083/ 的post的headers
        self.headers = {
            'Authorization': 'Bearer b276b551eb5ad18cbae3f10892427fff',  # 替换为你的 token 或其他 header
            'accept-encoding': 'gzip, deflate',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'content-type': 'application/json',
            'host': '172.19.64.168:8083',
            'request-origion': 'Knife4j',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
            'Base-Code': '2',  # 基地2 是Dallas，必传
            # 'Lang': 'en-US',  # 语言，必传
            'request-origion': 'Knife4j',
            # 'ss_staffNo': 'DA2410002'  # Elon Musk 的账号
        }

    def transform_dict_to_json(self, dict1: dict):
        json1 = json.dumps(dict1)
        print('转换dict为json..成功!')
        return json1

    def set_json_to_clipboard(self, target_input_json):  # TODO
        string1 = self.transform_dict_to_json(target_input_json)
        pyperclip.copy(string1)

    def post_one(self, uri, payload, taskName=''):
        url = self.target_server_url + uri
        msg = f'{getNowTime()} 开始进行数据构造和发送到 {url}'
        # 记录开始时间
        start_time = time.time()
        # 开始请求
        response = requests.post(url, headers=self.headers, json=payload)
        # 检查响应状态
        self.classPrint(Fore.BLUE + msg)
        # 记录结束时间
        end_time = time.time()
        # 计算运行时间并转换为毫秒
        execution_time_ms = (end_time - start_time) * 1000
        # 保留两位小数
        execution_time_ms = round(execution_time_ms, 2)
        if response.status_code == 200:
            self.classPrint(
                Fore.GREEN + f'{getNowTime()} {taskName} 成功，耗费时间：{execution_time_ms}毫秒')
            self.classPrint(Fore.WHITE + f'返回结果:' +
                            Fore.GREEN+f'{response.json()}')
        else:
            self.classPrint(
                Fore.RED + f'{getNowTime()} {taskName} 错误，耗费时间：{execution_time_ms}毫秒')
            self.classPrint(Fore.WHITE + f'返回结果:' +
                            Fore.RED+f'{response.json()}')
            print(Fore.RED + f'{getNowTime()} {taskName} 错误 \n',
                  response.status_code, response.text)

    def api_转序(self, productBatchNoList, process_id,  equipment_id):
        """将 某一个批次码 转序到 某个工序 且生产状态为排队

        Args:
            productBatchNoList (_type_): 批次码
            process_id (_type_): 工序id,比如
            equipment_id (_type_): 工序对应的设备id, 比如RLCS对应的设备为SP1RLCS0001
        """

        targetc_uri = '/test/createOrToProcess'
        target_input_json = {
            "equipment_id": "SP1RLCS0001",  # 设备*
            "operator_name": "",  # 操作人
            "process_id": "RLCS",  # 工序* XXSS RLCS
            "productBatchNoList": ['0IJ1BDCOL015015USE9C0001']  # 电芯条码列表*
        }
        target_input_json = {
            "equipment_id": equipment_id,  # 设备*
            "operator_name": "",  # 操作人
            "process_id": process_id,  # 工序* XXSS RLCS
            "productBatchNoList": productBatchNoList  # 电芯条码列表*
        }
        self.post_one(uri=targetc_uri,
                      payload=target_input_json,
                      taskName=f'将批次码{productBatchNoList}进行转序到{process_id}')

    def api_电芯出站(self, productBatchNoList='', process_id='', equipment_id=''):
        target_uri = '/deviceApi/checkProductMoveOut'
        target_input_json = {
            "batch_list": [  # 批次信息集合
                {
                    "channel_code": "",
                    "param_list": [  # 参数集合
                        {
                            "act_value": "839",  # 参数值
                            "param_code": "RLCS001"  # 参数名称
                        },
                        {
                            "act_value": "839",  # 参数值
                            "param_code": "RLCS002"  # 参数名称
                        },
                        {
                            "act_value": "839",  # 参数值
                            "param_code": "RLCS003"  # 参数名称
                        },
                        {
                            "act_value": "839",  # 参数值
                            "param_code": "RLCS004"  # 参数名称
                        },
                        {
                            "act_value": "839",  # 参数值
                            "param_code": "RLCS005"  # 参数名称
                        },

                    ],
                    "product_barcode": "0IJ1BDCOL015015USE9C0001"  # 箱码?批次码?
                }
            ],
            "end_time": getNowTime('%Y-%m-%d %H:%M:%S'),  # 结束时间
            "equipment_id": "SP1RLCS0001",  # 设备
            "operator_name": "",  # 操作人
            "process_id": "RLCS",  # 工序 , 下线水试 XXSS , 容量测试 RLCS
            "quality_status": 6  # 6 是复测， 7 是简容复测
        }
        self.post_one(uri=target_uri,
                      payload=target_input_json,
                      taskName=f'{target_uri} 将批次码{productBatchNoList} 在工序 {process_id} 中出站'
                      )

    def __repr__(self):
        return f'<{self.instanceName}:remarks>'


if __name__ == '__main__':
    target_input_json = {
        "batch_list": [  # 批次信息集合
            {
                "channel_code": "",
                "param_list": [  # 参数集合
                    {
                        "act_value": "RLCS005",  # 参数值
                        "param_code": "1"  # 参数名称
                    },

                ],
                "product_barcode": "0IJ1BDCOL015015USE9C0001"  # 箱码?批次码?
            }
        ],
        "end_time": getNowTime('%Y-%m-%d %H:%M:%S'),  # 结束时间
        "equipment_id": "SP1RLCS0001",  # 设备
        "operator_name": "",  # 操作人
        "process_id": "RLCS",  # 工序 , 下线水试 XXSS , 容量测试 RLCS
        "quality_status": 6  # 6 是复测， 7 是简容复测
    }
    newHelper = MES_Test_Api_Helper()

    batch_no = '0IJ1BDCOL015015USE9C0001'
    process_id = 'RLCS'  # 容量测试
    devices_id_RLCS = 'SP1RLCS0001'

    # batch_no = '0IJ1BDCOL015015USE9C0001'
    # process_id = 'XTTS'  # 系统调试
    # devices_id_RLCS = 'SP1XTTS'
    # newHelper.post_one(uri='/deviceApi/checkProductMoveOut',
    #                    payload=target_input_json, taskName='出站检验')
    # newHelper.api_转序([batch_no],  process_id, devices_id_RLCS)

    # 2024.12.05x 做一个电芯进站吧
    # newHelper.api_电芯进站开始() #还没有完成

    newHelper.api_电芯出站()
    target_input_json = {
        "batch_list": [  # 批次信息集合
            {
                "channel_code": "",
                "param_list": [  # 参数集合
                        {
                            "act_value": "1",  # 参数值
                            "param_code": "RLCS001"  # 参数名称
                        },
                    {
                            "act_value": "2",  # 参数值
                            "param_code": "RLCS002"  # 参数名称
                            },

                    {
                        "act_value": "1", "param_code": "RLCS007"},
                    {"act_value": "1", "param_code": "RLCS023"},
                    {"act_value": "1", "param_code": "RLCS011"},
                    {"act_value": "1", "param_code": "RLCS022"},
                    {"act_value": "1", "param_code": "RLCS009"},
                    {"act_value": "1", "param_code": "RLCS008"},
                    {"act_value": "1", "param_code": "RLCS013"},
                    {"act_value": "1", "param_code": "RLCS003"},
                    {"act_value": "1", "param_code": "RLCS010"},
                    {"act_value": "1", "param_code": "RLCS006"},
                    {"act_value": "1", "param_code": "RLCS020"},
                    {"act_value": "1", "param_code": "RLCS004"},
                    {"act_value": "1", "param_code": "RLCS021"},
                    {"act_value": "1", "param_code": "RLCS005"},
                ],
                "product_barcode": "0IJ1BDCOL015015USE9C0001"  # 箱码?批次码?
            }
        ],
        "end_time": getNowTime('%Y-%m-%d %H:%M:%S'),  # 结束时间
        "equipment_id": "SP1RLCS0001",  # 设备
        "operator_name": "",  # 操作人
        "process_id": "RLCS",  # 工序 , 下线水试 XXSS , 容量测试 RLCS
        "quality_status": 7  # 6 是复测， 7 是简容复测
    }
    target_input_json = {
        "batch_list": [  # 批次信息集合
            {
                "channel_code": "",
                "param_list": [  # 参数集合
                        {
                            "act_value": "1328",  # 参数值
                            "param_code": "RLCS001"  # 参数名称
                        },
                    {
                            "act_value": "1328",  # 参数值
                            "param_code": "RLCS002"  # 参数名称
                            },
                    {
                            "act_value": "1328",  # 参数值
                            "param_code": "RLCS003"  # 参数名称
                            },

                ],
                "product_barcode": "0IJ1BDCOL015015USE9C0001"  # 箱码?批次码?
            }
        ],
        "end_time": getNowTime('%Y-%m-%d %H:%M:%S'),  # 结束时间
        "equipment_id": "SP1RLCS0001",  # 设备
        "operator_name": "",  # 操作人
        "process_id": "RLCS",  # 工序 , 下线水试 XXSS , 容量测试 RLCS
        "quality_status": 7  # 6 是复测， 7 是简容复测
    }
    # newHelper.set_json_to_clipboard(target_input_json)
